package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.pojo.excel.DictData;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
@Slf4j
public class DictDataListener extends AnalysisEventListener<DictData> {
//    @Autowired  只能在组件类中使用(自动装配是从容器中获取对象)
    DictMapper dictMapper;

    public DictDataListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(DictData data, AnalysisContext context) {
        //读一行保存一行
        //将接受的数据转为数据库表映射的类型
        Dict dict = new Dict();
        //可以将有数据的对象的属性值拷贝给目标对象相同的属性并且类型需要一致
//        BeanUtils.copyProperties(data,dict);
        dict.setId(data.getId().longValue());
        dict.setParentId(data.getParentId().longValue());
        dict.setDictCode(data.getCode());
        dict.setName(data.getName());
        dict.setValue(data.getValue());
        //校验数据是否已存在： 如果id已存在 或者  parent_id+value 组合已存在 代表数据已存在
        Integer count = dictMapper.selectCount(new LambdaQueryWrapper<Dict>()
                .eq(Dict::getId, data.getId())
                .or(w->
                        w.eq(Dict::getParentId , data.getParentId())
                                .eq(Dict::getValue , data.getValue()
                                )
                )
        );
        if(count==0){
            log.info("新增数据:{}",dict);
            dictMapper.insert(dict);

        }
       // System.out.println("加载到数据: "+ data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
